<?php
namespace app\admin\controller;
use think\Db;
use think\Validate;
use app\admin\controller\Base;
use app\admin\model\Admin as AdminModel;
class Admin extends Base{
	public function index(){
		return $this->fetch();
	}

	public function lists(){
		$list=AdminModel::paginate(3);
		$this->assign('list',$list);
		return $this->fetch('list');
	}



	public function add(){
		if (request()->isPost()) {
			$data=[
				'username'=>input('username'),
				'password'=>md5(input('password')),
			];
			$validate= \think\Loader::validate('Admin');
			if (!$validate->scene('add')->check($data)) {
				return $this->error($validate->getError());
			}
			if (Db::name('admin')->insert($data)) {
				return $this->success('添加管理员成功！','lists');
			}else{
				return $this->error('添加管理员失败！');
			}
			return;
		}
		return $this->fetch('add');
	}

	public function edit(){
		$id=input('id');
		$res=db('admin')->find($id);
		if (request()->isPost()) {
			if (input('password')) {
					$password=md5(input('password'));
				}else{
					$password=$res['password'];
				}
			$data=[
				'id'=>input('id'),
				'username'=>input('username'),
				'password'=>$password,
			];
			//数据的校验 
			$validate= \think\Loader::validate('Admin');
			if (!$validate->scene('edit')->check($data)) {
				return $this->error($validate->getError());
			}

			$res=db('admin')->update($data);
			if ($res) {
				return $this->success('修改成功！','lists');
			}else{
				return $this->success('修改失败！');
			}
		}
		
		$this->assign('admin',$res);
		return $this->fetch('edits');
	}

	public function delete(){
		$id=input('id');
		if ($id!=20) {
			$res=db('admin')->delete($id);
			if ($res) {
				$this->success("删除成功！",'lists');
			}else{
				$this->success("删除失败！",'');
			}
		}else{
			$this->error('初始化管理员不能删除！');
		}
		
	}

	public function logout(){
		session(null);
		$this->success('退出成功！','login/index');
	}

}
?>